import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

// 测试 api.test
// 正式 rticle.api
import axios from '@/store/ajax.js'
// import eventBus from './eventBus.js';
import eventBus from '@/common/event-bus.js'
const webSocketStore = new Vuex.Store({
	state: {
		ws: null, // socket 对象
		wsUrl: 'ws://47.93.43.172:8282', // 地址
		reconnectNum: 3, // 重连最大次数
		socketState: 'init', // socket 状态 默认初始化 init:初始化 wait:等待响应  connect:连接 close:关闭
		aliveInterval: null, // 心跳定时器
		sendQueue: [], // 发送队列
		room_no: '',
		count: '',
		chatList: [],
		userInfo: uni.getStorageSync('userInfo') || {},
		_$cartList: [],
		live_pull_url: '',
		anchor: {},
		pushGoodsData: {}
	},
	mutations: {
		setCartList(state) {

		},
		setRoomNo(state, val) {

			state.room_no = val.id
			state.live_pull_url = val.live_pull_url
			state.anchor = val.anchor

		},
		setUserInfo(state) {
			axios('Center/main', "POST", 'member').then(res => {
				if (res.data.code == 200) {
					uni.setStorageSync('userInfo', res.data.data.member)
					console.log('state.userInfo', state.userInfo);
				}
			})

			// state.userInfo=data
		},
		sendWebSocket(state, data) {
			if (state.ws && state.socketState === 'connect') {
				uni.sendSocketMessage({
					data: JSON.stringify(data),
					success: () => {
						if (data.type == 'say') {
							// state.chatList.push(data)
							// uni.$emit('chatListEvent', state.chatList)
						}

					},
					fail: (err) => {
						console.error('消息发送失败:', err);
					}
				});
			} else {
				console.error('WebSocket 未连接或连接已关闭，无法发送消息');
			}
		},
		initSocket(state) {
			state.socketState = 'wait';
			console.log('zhixing');
			state.ws = uni.connectSocket({
				url: state.wsUrl,
				success: () => {
					// uni.showToast({
					// 	title: '创建成功时',
					// 	icon: 'success',
					// 	duration: 2000
					// });
					state.socketState = 'connect';
					webSocketStore.commit('keepAlive', state);
					webSocketStore.commit('getMid');
				},
				fail: (err) => {
					console.error('WebSocket 连接失败:', err);
				}
			});

			uni.onSocketOpen(() => {
				console.log('WebSocket 连接已打开');
			});

			uni.onSocketMessage((res) => {
				const data = JSON.parse(res.data);
				console.log('收到消息:', data)
				if (data.type == 'online_update') {
					state.count = data.count
					uni.$emit('countEvent', state.count)

				} else if (data.type == 'push_goods') {
					state.pushGoodsData = data.data
					uni.$emit('pushGoodsEvent', state.pushGoodsData)
				} else if (data.type == 'close_goods') {
					state.pushGoodsData = {}
					uni.$emit('pushGoodsEvent', state.pushGoodsData)
				} else if (data.type == 'say') {
					data.data.time = new Date * 1
					state.chatList.push(data.data)
					uni.$emit('chatListEvent', state.chatList)
				}
			});

			uni.onSocketClose((e) => {
				state.socketState = 'close';
				console.log("close", e);
				console.log("WebSocket 连接关闭");
				if (state.aliveInterval) {
					clearInterval(state.aliveInterval);
					state.aliveInterval = null;
				}
				if (e.code === 1000) {
					if (state.reconnectNum) {
						state.reconnectNum--;
						setTimeout(() => {
							webSocketStore.commit('initSocket');
						}, 60000);
					}
				} else {
					console.error("WebSocket 异常连接关闭，停止连接");
				}
			});

			uni.onSocketError((e) => {
				console.log('WebSocket 连接错误:', e);
			});
		},
		keepAlive(state) {
			// 定时发送心跳包
			state.aliveInterval = setInterval(() => {
				let data = {
					type: "ping"
				};
				uni.sendSocketMessage({
					data: JSON.stringify(data),
					success: () => {
						// console.log('心跳包发送成功');
					},
					fail: (err) => {
						// console.error('心跳包发送失败:', err);
					}
				});
			}, 300000);
		},

		getMid(state) {
			axios('Center/main', "POST", 'member').then(res => {
				console.log('res.....................', res.data.data);
				if (res.data.code == 200) {
					// state.mid=res.data.data.mid

					let data = {
						"type": "login",
						"data": {
							"user_id": res.data.data.member.id,
							"room_no": state.room_no
						}

					}
					//
					webSocketStore.commit('sendWebSocket', data);
				}
			})
		},
		disconnectWebSocket(state) {
			if (state.ws) {
				uni.closeSocket({
					success: () => {
						console.log('WebSocket 连接已断开');
						state.socketState = 'close';
						if (state.aliveInterval) {
							clearInterval(state.aliveInterval);
							state.aliveInterval = null;
						}
					},
					fail: (err) => {
						console.error('断开 WebSocket 连接失败:', err);
					}
				});
			} else {
				console.error('WebSocket 未连接，无需断开');
			}
		}

	}
});

export default webSocketStore;